<template>
    <div>
        <el-row>
            <el-form :inline="true" ref="form" :model="form" label-width="66px" class="demo-form-inline" clo>
                <el-form-item prop="title">
                    <el-input size="mini" placeholder="请输入素材名称" v-model="form.title"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="search" size="mini">筛选</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row>
            <el-row v-if="hasPermission('kanke:textbook:material:update-transcode')">
                <p class="tip">手动更新转码状态, 需要上传文件半小时之后才可以操作, 大文件转码时间比较长,请耐心等待!</p>
            </el-row>
            <el-row>
                <Upload :type="type" @onFinish="init" v-if="hasPermission('kanke:textbook:material:upload')" />
                <pers-button icon="" size="mini" @click="handleBatchDel()" perms="kanke:textbook:material:batch-del"
                    type="warning" label="批量删除"></pers-button>

                <pers-button icon="" size="mini" @click="handleUpdateUrl()"
                    perms="kanke:textbook:material:update-transcode" type="success" label="更新转码"></pers-button>


                <pers-button icon="" size="mini" @click="handleCutUpload()"
                    perms="kanke:textbook:material:update-transcode" type="warning" label="截图上传"></pers-button>
            </el-row>
            <el-table :data="tableData" v-loading="loading" size="mini" style="width: 100%;margin-bottom: 20px;"
                @selection-change="handleSelectionChange" row-key="id" border stripe default-expand-all>
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column prop="title" label="文件名" header-align="center" align="center"></el-table-column>
                <el-table-column prop="transcode_type" label="转码状态(仅 视频|音频)" header-align="center" align="center">
                    <template slot-scope="scope">
                        <div>
                            {{ transcodeType[scope.row.transcode_type] || '-' }}
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="create_time" label="创建时间" header-align="center" align="center"></el-table-column>
                <el-table-column prop="creater_name" label="创建人" header-align="center" align="center"></el-table-column>

                <el-table-column prop="state" label="操作" header-align="center" align="center"
                    v-if="isShow(['kanke:textbook:material:download', 'kanke:textbook:material:rename', 'kanke:textbook:material:del'])">
                    <template slot-scope="scope">
                        <PersButton type="text" perms="kanke:textbook:material:download"
                            :label="scope.row.type == 1 ? '下载' : ' 预览'" @click="handlePreview(scope.row)" />
                        <PersButton type="text" perms="kanke:textbook:material:rename" label="重命名"
                            @click="handleEdit(scope.row)" />

                        <PersButton type="text" perms="kanke:textbook:material:del" label="删除"
                            @click="handleBatchDel(scope.row.id)" />
                    </template>
                </el-table-column>
            </el-table>
            <div class="block">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pageInfo.pageNumber" :page-sizes="pageSizes" :page-size="pageInfo.pageSize"
                    background layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total">
                </el-pagination>
            </div>
        </el-row>
        <preview @close="previewItem = {}" v-if="previewItem.id" :item="previewItem" />
        <CutImgUpload v-if="cutUpload" :visible.sync:="cutUpload" @onFinish="handleCutFinish" />
    </div>
</template>
<script>
import { hasPermission, isShow } from '@/common/permission';
import { getList, batchDelete, update, updateMaterialUrl } from '@/api/kanke/textbook/material'
import { pageSizes } from '@/constant/index.js'
import Preview from './Preview.vue'
import Upload from './Upload.vue';
import CutImgUpload from './CutImgUpload.vue';

export default {
    // 1=>文档,2=>视频;3=>音频;4=>图片

    name: "KanKeMaterialTabPane",
    props: {
        type: {
            type: String,
            default: 'all'
        }
    },
    components: {
        Preview,
        Upload,
        CutImgUpload
    },
    data() {
        return {
            loading: false,
            form: {
                title: '',
            },
            tableData: [],
            pageInfo: {
                pageNumber: 1,
                pageSize: 10,
                total: 0
            },
            pageSizes,
            multipleSelection: [],
            multipleVal: [],
            multipleItemArr: [],
            transcodeType: {
                1: '转码中',
                2: '转码完成',
                3: '转码失败'
            },
            typeMap: {
                'all': '',
                'doc': 1,
                'video': 2,
                'audio': 3,
                'image': 4
            },
            previewItem: {},
            showPreview: false,
            cutUpload: false

        }
    },
    watch: {
        type: {
            handler(newVal) {
                if (newVal) {
                    this.init()
                }
            },
            immediate: true
        }
    },
    methods: {
        hasPermission,
        isShow,
        init() {
            this.loading = true
            const type = this.typeMap[this.type]
            const params = {
                type,
                title: this.form.title,
                ...this.pageInfo
            }
            getList(params).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data.data
                    this.pageInfo.total = res.data.total
                }
                this.loading = false
            })
        },
        handleCutFinish() {
            this.cutUpload = false
            this.init()
        },
        handleCutUpload() {
            this.cutUpload = true
        },
        add() { },
        search() {
            this.pageInfo.pageNumber = 1;
            this.init()
        },
        handleSizeChange(e) {
            this.pageInfo.pageSize = e
            this.init()
        },
        handleCurrentChange(e) {
            this.pageInfo.pageNumber = e
            this.init()
        },
        handleSelectionChange(val) {
            this.multipleItemArr = [...val]
            if (val.length) {
                this.multipleSelection = val.map(item => item.id)

                this.multipleVal = val.map(item => item.file_url)
            } else {
                this.multipleVal = [];
            }
            this.$emit('childEvent', this.multipleVal, val);
        },
        handlePreview(row) {
            if ([2, 3].includes(row.type) && row.transcode_type == 1) {
                this.$message.error('文件转码中，无法预览')
                return false;
            }
            if (row.type == 1) {
                // 文档类型 直接下载
                if (row.file_url) {
                    const a = document.createElement('a')
                    a.href = row.file_url
                    a.click()
                    a.remove()
                }
                return false;
            }
            this.showPreview = true;
            this.previewItem = { ...row }
        },
        handleEdit({ id }) {
            // 谈个小框让用户输入一个文件名
            this.$prompt('请输入文件名', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^.{1,100}$/, //不能为空, 长度 不超过 100
                inputErrorMessage: '文件名不合法'
            }).then(({ value }) => {

                this.loading = true
                update({ id, title: value }).then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        this.$message.success('重命名成功')
                        this.init()
                    } else {
                        this.$message.error('重命名失败')
                    }
                }).catch(() => { this.loading = false })
            })

        },
        handleBatchDel(delId = 0) {
            let id_arr = [];
            if (!delId) {
                if (!this.multipleSelection.length) {
                    this.$message.warning('请选择要删除的数据')
                    return;
                }
                id_arr = [...this.multipleSelection];
            } else {
                id_arr = [delId];
            }


            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loading = true
                batchDelete({ id_arr }).then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        this.$message.success('删除成功')
                        if (!delId) {
                            this.multipleSelection = []
                        }
                        this.init()
                    } else {
                        this.$message.error('删除失败')
                    }
                })

            }).catch(() => {
                this.loading = false
            })
        },
        handleUpdateUrl() {
            if (!this.multipleItemArr.length) {
                this.$message.warning('请选择要同步的文件')
                return;
            }
            let showError = false;
            let errMsg = '';
            this.multipleItemArr.map(item => {
                // if (item.transcode_type == 2) {
                //     showError = true;
                //     errMsg = '不能选择转码成功的文件!'
                // }
                if (item.save_type == 1) {
                    showError = true;
                    errMsg = '只能选择视频或音频文件!'
                }
                // 判断create_time 不能小于一个小时
                if (item.create_time) {
                    let nowTime = new Date().getTime();
                    let createTime = new Date(item.create_time).getTime();
                    let diffTime = nowTime - createTime;
                    if (diffTime < 1800000) {
                        showError = true;
                        errMsg = '文件创建时间需要超过半小时!'
                    }
                }
            })
            if (showError) {
                this.$message.error(errMsg);
                return;
            }
            const file_id_arr = [...this.multipleItemArr.map(item => item.file_id)];
            this.$confirm('手动更新文件转码状态, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loading = true
                updateMaterialUrl({ file_id_arr }).then(res => {
                    if (res.code == 200) {
                        this.$message.success('更新成功')
                        this.multipleSelection = []
                        this.multipleItemArr = []
                        this.loading = false
                        this.init()
                    } else {
                        this.$message.error('更新失败')
                        this.loading = false
                    }
                }).catch(() => {
                    this.loading = false
                })

            }).catch(() => {
                this.loading = false
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.tip {
    margin: 0;
    color: red;
}
</style>